package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.SignUpPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.SignUpViewImpl;
import com.beiing.tianshuai.tianshuai.util.Clickable;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.MD5Utils;
import com.beiing.tianshuai.tianshuai.util.RegexUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;

import java.text.MessageFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * Create by Jinni 2017-07-13 08:55:43
 * <p>注册界面</p>
 */
public class SignUpActivity extends BaseActivity implements SignUpViewImpl {

    private static final String TAG = "SignUpActivity";
    private Context mContext;
    private SignUpPresenter mPresenter;
    private Unbinder mUnbinder;
    private TimeCount mCountDown;
    private int mRequestType; // 0-获取验证码 1-提交注册

    @BindView(R.id.cb_agree_warning)
    CheckBox mCbAgreeWarning;                           // 用户协议
    @BindView(R.id.toolbar)
    Toolbar mToolbar;                                   // 标题栏
    @BindView(R.id.toolbar_iv_back)
    ImageView mBack;                                    // 返回
    @BindView(R.id.txt_agree_warning)
    TextView mAgreeWarning;                             // 使用条款提示
    @BindView(R.id.btn_sign_up)
    TextView mSignUp;                                   // 注册
    @BindView(R.id.edit_sign_up_username)
    EditText mUsername;                                 // 账号
    @BindView(R.id.edit_safe_code)
    EditText mSafeCode;                                 // 验证码
    @BindView(R.id.btn_get_safe_code)
    TextView mGetCode;                                  // 获取验证码
    @BindView(R.id.edit_sign_up_password)
    EditText mPassword;                                 // 密码

    @Override
    protected int getLayoutId() {
        return R.layout.activity_signup;
    }

    @Override
    protected void init() {
        mContext = this;
        mUnbinder = ButterKnife.bind(this);
        initStatusBar();
        initAgreeWarning();
        initListener();
        initPresenter();
    }

    private void initStatusBar() {
//        XStatusBarHelper.setStatusBarDarkMode(this);
    }

    /**
     * 设置同意条款提示中可点击文字的文字颜色和点击事件
     */
    private void initAgreeWarning() {
        mAgreeWarning.setHighlightColor(Color.parseColor("#00000000"));
        SpannableString spannableString = new SpannableString(mAgreeWarning.getText().toString());
        spannableString.setSpan(new Clickable(clickListener), 6, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#67a0ff")), 6, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mAgreeWarning.setText(spannableString);
        mAgreeWarning.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void initListener() {
        // 返回按钮
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 注册按钮
        mSignUp.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if (isEditComplete()) {
                    String number = mUsername.getText().toString();
                    mRequestType = 1;
                    mPresenter.isAlreadySignUp(number);
                }
            }
        });

        // 获取验证码
        mGetCode.setOnClickListener(new View.OnClickListener() {

            private String mNumber;

            @Override
            public void onClick(View view) {
                mGetCode.setClickable(false);
                mNumber = mUsername.getText().toString();
                if (RegexUtils.checkMobile(mNumber)) {
                    mRequestType = 0;
                    mPresenter.isAlreadySignUp(mNumber);
                } else {
                    showShortText("手机号格式不正确");
                    mGetCode.setClickable(true);
                }
            }
        });
    }

    private void initPresenter() {
        mPresenter = new SignUpPresenter(this);
    }

    /**
     * 使用条款
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showShortText("用户协议");
        }
    };

    /**
     * 判断是否填写完整信息
     */
    private boolean isEditComplete() {
        if (TextUtils.isEmpty(mUsername.getText())) {
            showShortText("请填写账号");
            return false;
        }
        if (TextUtils.isEmpty(mSafeCode.getText())) {
            showShortText("请填写验证码");
            return false;
        }
        if (TextUtils.isEmpty(mPassword.getText())) {
            showShortText("请填写密码");
            return false;
        }
        if (!mCbAgreeWarning.isChecked()) {
            showShortText("请阅读并同意用户协议");
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        mPresenter.onUnsubscribe();
        if (mCountDown != null) {
            mCountDown.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "加载中，请稍后...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(CodeBean signUpBean) {
        if (signUpBean.getCode() == 200) {
            showShortText("注册成功");
            finish();
        } else {
            if (signUpBean.getCode() == 405) {
                showShortText("验证码错误");
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        showShortText("网络异常");
    }

    @Override
    public void getSignUpCode(CommonBean signUpBean) {
        LogUtils.i(signUpBean.getCode() + "\n" + signUpBean.getData().getNumber(), TAG);
        if (signUpBean.getCode() == 401) {
            showShortText("请求频繁，请稍后再试。");
            mGetCode.setClickable(true);
        } else {
            showShortText("获取成功");
            mCountDown = new TimeCount(60000, 1000);
            mCountDown.start();
        }
    }

    /**
     * code = 200 已注册
     * code = 400 未注册
     *
     * @param bean 请求结果
     */
    @Override
    public void isAlreadySignUp(CommonBean bean) {
        int code = bean.getCode();
        String number = mUsername.getText().toString();
        switch (code) {
            case 200:
                showShortText("该账号已注册");
                break;
            case 400:
                if (mRequestType == 0) {
                    mPresenter.getSignUpCode(number);
                } else {
                    String time = getTime();
                    mPresenter.getSignUpResult(
                            mSafeCode.getText().toString().trim(),
                            mUsername.getText().toString().trim(),
                            "TIANSHUAI" + time,
                            MD5Utils.getMd5Value(mPassword.getText().toString().trim()),
                            time
                    );
                }
                break;
            default:
        }
    }

    /**
     * 获取当前系统时间的时间戳
     *
     * @return 时间戳
     */
    public String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        return String.valueOf(time);
    }

    /**
     * 获取验证码计时器
     */
    private class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mGetCode.setText("重新获取");
            mGetCode.setTextColor(ContextCompat.getColor(mContext, R.color.text_login_main_color));
            mGetCode.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mGetCode.setClickable(false);
            long l = millisUntilFinished / 1000;
            mGetCode.setText(MessageFormat.format("{0}秒", String.valueOf(l)));
            mGetCode.setTextColor(ContextCompat.getColor(mContext, R.color.text_login_main_color));
        }
    }
}
